import express, { response } from 'express'
import path from 'path'
import connection from './MySQL'
import uuid from 'uuid'
import fs from 'fs'

let filePath = path.join(__dirname, './public')
let app = express() //创建express服务器
app.use(  //处理静态资源
    express.static(filePath)
)
const bodyParser = require('body-parser');
app.use(bodyParser.json({ limit: '50mb' }));//数据JSON类型
app.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));//解析post请求数据
app.all('*', function (req, res, next) {
    let origin = req.headers.origin;
    res.setHeader('Access-Control-Allow-Origin', "*");
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    next();
})
const jwt = require('jsonwebtoken'); //引入jwt模块


// 数据库连接测试
connection.connect(() => {
    console.log('数据库已连接');
})

// ----------------------------------------------------------------------------------------
  
app.post('/login', (req, res) => {
    var {username, password} = req.body
    connection.query(`select * from author where authorUser='${username}' or authorWord='${password}'`, (error,response) => {
        if(response && response.length !==0){
            if(response[0].authorWord === req.body.password){
                delete response[0].authorWord 
                 //定义token的有限载荷
                const payload = { name:response.authorId}
                 //给定密钥
                const secret = 'deyun'
                 //定义token
                const token = jwt.sign(payload,secret,{'expiresIn':1440})// 设置过期时间
                res.send({code:"1",msg:"登录成功", data:response[0], token:token, user_name:req.body.username})
                
            }else {
                res.send({code:"2",msg:"密码错误"})
            }
        }else{
            
            res.send({code:"2",msg:"账号未注册"})
        }
    })
});

// ----------------------------------------------------------------------------------------
//设置服务器端口号
app.listen(7000, () => {
    console.log("服务器连接成功");
    console.log('http://localhost:7000')
})
